package dao;

import java.awt.Image;
import java.sql.*;
import java.util.List;
import java.util.ArrayList;

/**
 * Created by IntelliJ IDEA.
 * User: Admin
 * Date: 11.05.2009
 * Time: 15:47:29
 * To change this template use File | Settings | File Templates.
 */
public class DaoImpl implements Dao{
     private final String url = "jdbc:sqlserver://";
     private final String serverName= "localhost";
     private final String portNumber = "1433";
     private final String databaseName= "images";
     private final String userName = "PAVEL\\Admin";
     private final String password = "";
     private final String selectMethod = "cursor";
     private ResultSet resultSet;
     private Statement statement;

    public DaoImpl() {
        try {
            statement = getConnection().createStatement(
                ResultSet.TYPE_SCROLL_INSENSITIVE,
                ResultSet.CONCUR_UPDATABLE);
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }

    public List<Image> getImages() {
        List<Image> images = null;
        try {
            resultSet = statement.executeQuery("SELECT image FROM images");
            images = new ArrayList<Image>();
            if (resultSet != null) {
                while (resultSet.next()) {
                        images.add((Image) resultSet.getObject(0));
                }
            }
        } catch (SQLException exception) {
            System.out.println(exception.getMessage());
        }
        return images;
    }

    public void saveImage(Image image) {
        try {
            resultSet.moveToInsertRow();
            resultSet.updateObject(1, image);
            resultSet.updateRow();
        } catch (SQLException exception) {
            System.out.println(exception.getMessage());
        }
    }

    private Connection getConnection() {
        String connectionString = url+serverName+":"+portNumber+
                ";databaseName="+databaseName+";selectMethod="+selectMethod+";";
        Connection connection = null;
        try {
//            DriverManager.registerDriver(
//                    DriverManager.getDriver("E:\\current\\project\\sqljdbc.jar"));
            connection = DriverManager.getConnection(connectionString, userName, password);
        } catch (SQLException exception) {
            System.out.println(exception.getMessage());
        }
        return connection;
    }
}
